package br.ufrj.dcc.tp.client;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.HashSet;
import java.util.Set;

import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;

import br.ufrj.dcc.tp.common.Client;
import br.ufrj.dcc.tp.common.Message;

public class ClientThreadMessageReceiver extends Thread {

	private Client client;
	private Socket socket;
	
	public ClientThreadMessageReceiver(Client client, Socket socket) {
		this.client = client;
		this.socket = socket;
		// envia cliente
        try {
        	ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
			out.writeObject(client);
	        out.flush();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
		System.out.println("[ClientThreadReceiver] Initialize sucessfully!");
	}
	
	/**
	 * Responsável por receber a mensagem enviada pelo servidor e imprimir na tela
	 * */
	@Override
	public void run() {
		System.out.println("[ClientThreadReceiver] Starting run() method.. ");
		try {
    		
			ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
			Object obj;
			while((obj = in.readObject()) != null) {
				if (obj instanceof Message) {
					Document doc = ClientFactory.getMainViewInstance().getTxtListMessages().getDocument();
					
					SimpleAttributeSet keyword = new SimpleAttributeSet();
					StyleConstants.setBold(keyword, true);
					
					SimpleDateFormat format = new SimpleDateFormat("[dd-MMMM-yyyy HH:mm]");
					String date = format.format(((Message)(obj)).getDate());
					
					doc.insertString(doc.getLength(), date + " " + ((Message)(obj)).getFromClient() + " escreveu: \n", keyword);
					StyleConstants.setBold(keyword, false);
					StyleConstants.setItalic(keyword, true);
					
					doc.insertString(doc.getLength(), ((Message)(obj)).getMessage() + "\n", keyword);
					
					in = new ObjectInputStream(socket.getInputStream());
				} else if (obj instanceof Object[]) {
					Set<String> set = new HashSet<String>();
					for(int i=0; i < ((Object[])obj).length;i++) {
						String name = ((Client)((Object[])obj)[i]).getName();
						if (((Client)((Object[])obj)[i]).equals(client)) name += " (me)";
						set.add(name);
					}
					ClientService.getInstance().updateList(set);
					in = new ObjectInputStream(socket.getInputStream());
				}
			}
			
    	}catch(IOException e) {
    		System.out.println("[ClientThreadReceiver] Receiving from server failed");
    		e.printStackTrace();
    	} catch (ClassNotFoundException e) {
    		System.out.println("[ClientThreadReceiver] Receive object from server failed");
			e.printStackTrace();
		} catch (BadLocationException e) {
			System.out.println("[ClientThreadReceiver] Failed to append text");
			e.printStackTrace();
		}
		
	}
	
}
